﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KC.DataAccess.Processor;

namespace KC.Presentation.ProcessAggregator.Plugins
{
	public partial class RssAccumulatorForm : UserControl
	{
		public RssAccumulatorForm()
		{
			InitializeComponent();
			dc = new ProcessorDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["Processor"].ConnectionString);
		}
		ProcessorDataContext dc;

		private void RssAccumulatorForm_Load(object sender, EventArgs e)
		{
			timer1 = new Timer();
			timer1.Interval = 5000;
			timer1.Enabled = true;
			timer1.Tick += new EventHandler(timer1_Tick);
			timer1.Start();
			webBrowser1.ScriptErrorsSuppressed = true;
		}

		private void timer1_Tick(object sender, EventArgs e)
		{

			int idx = lbItems.SelectedItem == null ? -1 : ((RssItem)lbItems.SelectedItem).ID;
			UpdateContent();

			if (cbLive.Checked)
				Rotate();
			else  {
				if (idx > -1)
					foreach (RssItem ri in lbItems.Items)
						if (ri.ID == idx) {
							lbItems.SelectedItem = ri;
							break; } }
		}

		private void UpdateContent()
		{
			lbItems.DataSource = (from ri in dc.RssItems
								  orderby ri.ID descending
								  select ri).Take(255);
		}
		private void Rotate()
		{
			int ran = new Random().Next(0, lbItems.Items.Count - 1);
			lbItems.SelectedIndex = ran;
		}

		private void lbItems_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (Environment.StackTrace.Contains("timer1_Tick") && !Environment.StackTrace.Contains("Rotate()"))
				return;

			string url = ((RssItem)lbItems.SelectedItem).URL;
			webBrowser1.Navigate(url);
			txtAddress.Text = url;
			if (webBrowser1.Document != null && webBrowser1.Document.Body != null)
				webBrowser1.Document.Body.ScrollIntoView(true);
		}

	}
}
